package com.novice.config;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.net.Inet4Address;
import java.net.InetAddress;

@Slf4j
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Knife4jConfig implements ApplicationListener<WebServerInitializedEvent> {
    private final static String PROJECT_NAME = "Nacos Demo===> 订单微服务"; // web浏览器tab标题
    private final static String PROJECT_VERSION = "V1.0";

    @Bean
    public Docket adminApiConfig() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("orderApi")
                .apiInfo(adminApiInfo())
                .select()
                // 指定@ApiOperation标注的接口被加入文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//                .apis(RequestHandlerSelectors.basePackage("com.novice.**"))
                .paths(PathSelectors.any())
                //只显示admin路径下的页面
//                .paths(PathSelectors.regex("/auth/.*"))
                .build();
    }

    private ApiInfo adminApiInfo() {
        return new ApiInfoBuilder()
                .title(PROJECT_NAME + "-API文档")
                .description("描述本系统提供的对外接口说明")
                .version(PROJECT_VERSION)
                .build();
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        try {
            InetAddress inetAddress = Inet4Address.getLocalHost();
            String contextPath = event.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path");
            log.info("[" + PROJECT_NAME + "-项目启动成功！接口文档地址: http://"
                    + inetAddress.getHostAddress() + ":" + event.getWebServer().getPort()
                    + (StringUtils.isBlank(contextPath) ? "" : contextPath) + "/doc.html\033[0m");
        } catch (Exception e) {
            log.error("接口文档搭建失败", e);
        }
    }
}
